<template>
  <div class="orders-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" :inline="true">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="statistics-container">
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-title">今日订单数</div>
          <div class="statistics-value">{{ statistics.todayCount }}</div>
          <div class="statistics-compare">较昨日 <span :class="statistics.countCompare >= 0 ? 'up' : 'down'">{{ statistics.countCompare >= 0 ? '+' : '' }}{{ statistics.countCompare }}%</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-title">今日销售额</div>
          <div class="statistics-value">¥{{ statistics.todaySales.toFixed(2) }}</div>
          <div class="statistics-compare">较昨日 <span :class="statistics.salesCompare >= 0 ? 'up' : 'down'">{{ statistics.salesCompare >= 0 ? '+' : '' }}{{ statistics.salesCompare }}%</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-title">待发货订单</div>
          <div class="statistics-value">{{ statistics.pendingShipment }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-title">待收货订单</div>
          <div class="statistics-value">{{ statistics.pendingReceipt }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="orderNo" label="订单号" min-width="180" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="totalAmount" label="订单金额" width="120" sortable>
          <template #default="scope">
            <span>¥{{ Number(scope.row.totalAmount).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="scope">
            <el-tag type="info">{{ getPaymentMethodText(scope.row.paymentMethod) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180" sortable />
        <el-table-column prop="payTime" label="支付时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleDetail(scope.row)">详情</el-button>
            <el-button
              v-if="scope.row.status === 'paid'"
              size="small"
              type="success"
              link
              @click="handleShip(scope.row)"
            >
              发货
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending_payment'"
              size="small"
              type="warning"
              link
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button
              v-if="['pending_shipment', 'shipped'].includes(scope.row.status)"
              size="small"
              type="info"
              link
              @click="handleLogistics(scope.row)"
            >
              物流
            </el-button>
            <el-button
              v-if="scope.row.status === 'completed' || scope.row.status === 'cancelled'"
              size="small"
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 物流信息对话框 -->
    <el-dialog v-model="logisticsVisible" title="物流信息" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="物流公司">{{ logistics.company }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ logistics.trackingNo }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ logistics.shipTime }}</el-descriptions-item>
      </el-descriptions>

      <el-timeline class="logistics-timeline">
        <el-timeline-item
          v-for="(item, index) in logistics.records"
          :key="index"
          :timestamp="item.time"
          :type="index === 0 ? 'primary' : ''"
        >
          {{ item.content }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog v-model="shipDialogVisible" title="发货" width="500px">
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="120px"
      >
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰快递" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通快递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
            <el-option label="邮政EMS" value="EMS" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Delete, Check, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getOrderList, getOrderDetail, updateOrderStatus } from '@/api/shop'

const router = useRouter()

// 数据加载状态
const loading = ref(false)
const submitLoading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格数据
const tableData = ref([])

// 订单状态选项
const orderStatusOptions = [
  { value: 'pending_payment', label: '待付款' },
  { value: 'paid', label: '已付款' },
  { value: 'pending_shipment', label: '待发货' },
  { value: 'shipped', label: '已发货' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' },
  { value: 'refunding', label: '退款中' },
  { value: 'refunded', label: '已退款' }
]

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  username: '',
  phone: '',
  status: '',
  dateRange: []
})

// 统计数据
const statistics = reactive({
  todayCount: 125,
  countCompare: 12.5,
  todaySales: 15863.50,
  salesCompare: -5.2,
  pendingShipment: 36,
  pendingReceipt: 58
})

// 物流信息
const logisticsVisible = ref(false)
const logistics = ref({
  company: '',
  trackingNo: '',
  shipTime: '',
  records: []
})

// 发货对话框
const shipDialogVisible = ref(false)
const shipFormRef = ref(null)
const shipForm = reactive({
  orderId: '',
  company: '',
  trackingNo: ''
})

const shipRules = {
  company: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
  trackingNo: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 'pending_payment':
      return 'warning'
    case 'paid':
    case 'pending_shipment':
      return 'success'
    case 'shipped':
      return 'info'
    case 'completed':
      return 'success'
    case 'cancelled':
      return 'danger'
    case 'refunding':
      return 'warning'
    case 'refunded':
      return 'info'
    default:
      return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 'pending_payment':
      return '待付款'
    case 'paid':
      return '已付款'
    case 'pending_shipment':
      return '待发货'
    case 'shipped':
      return '已发货'
    case 'completed':
      return '已完成'
    case 'cancelled':
      return '已取消'
    case 'refunding':
      return '退款中'
    case 'refunded':
      return '已退款'
    default:
      return '未知'
  }
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  switch (method) {
    case 'alipay':
      return '支付宝'
    case 'wechat':
      return '微信支付'
    case 'bank':
      return '银行卡'
    default:
      return '未知'
  }
}

// 获取订单列表
const fetchData = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API
    // const { data } = await getOrderList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   orderNo: searchForm.orderNo,
    //   username: searchForm.username,
    //   phone: searchForm.phone,
    //   status: searchForm.status,
    //   startDate: searchForm.dateRange && searchForm.dateRange.length ? searchForm.dateRange[0] : null,
    //   endDate: searchForm.dateRange && searchForm.dateRange.length ? searchForm.dateRange[1] : null
    // })
    // tableData.value = data.list
    // total.value = data.total
    
    // 模拟数据
    setTimeout(() => {
      const statuses = ['pending_payment', 'paid', 'pending_shipment', 'shipped', 'completed', 'cancelled']
      const paymentMethods = ['alipay', 'wechat', 'bank']
      
      const mockData = Array.from({ length: 20 }).map((_, index) => {
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        
        return {
          id: index + 1,
          orderNo: `ORD${String(2023050000 + index).padStart(10, '0')}`,
          username: `user${Math.floor(Math.random() * 1000)}`,
          phone: `1${Math.floor(Math.random() * 9 + 1)}${String(Math.floor(Math.random() * 10000000000)).padStart(10, '0')}`.slice(0, 11),
          totalAmount: (Math.random() * 500 + 50).toFixed(2),
          status,
          paymentMethod: paymentMethods[Math.floor(Math.random() * paymentMethods.length)],
          createTime: '2023-05-20 10:30:00',
          payTime: status === 'pending_payment' ? null : '2023-05-20 10:35:00'
        }
      })
      
      tableData.value = mockData
      total.value = 100
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取订单列表失败', error)
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  fetchData()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 查看订单详情
const handleDetail = (row) => {
  router.push(`/shop/orders/${row.id}`)
}

// 发货
const handleShip = (row) => {
  shipForm.orderId = row.id
  shipForm.company = ''
  shipForm.trackingNo = ''
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = () => {
  shipFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      // 实际应用中应该调用API
      // await updateOrderStatus(shipForm.orderId, {
      //   status: 'shipped',
      //   logisticsCompany: shipForm.company,
      //   trackingNo: shipForm.trackingNo
      // })
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '发货成功'
      })
      
      // 关闭对话框并刷新数据
      shipDialogVisible.value = false
      fetchData()
    } catch (error) {
      console.error('发货失败', error)
      ElMessage({
        type: 'error',
        message: '发货失败'
      })
    } finally {
      submitLoading.value = false
    }
  })
}

// 查看物流
const handleLogistics = (row) => {
  // 实际应用中应该调用API获取物流信息
  // const { data } = await getLogisticsInfo(row.id)
  // logistics.value = data
  
  // 模拟数据
  logistics.value = {
    company: '顺丰快递',
    trackingNo: `SF${Math.floor(Math.random() * 1000000000)}`,
    shipTime: '2023-05-21 09:30:00',
    records: [
      { time: '2023-05-23 14:30:00', content: '已签收，签收人：本人' },
      { time: '2023-05-23 11:20:00', content: '快件已到达[北京市海淀区西二旗站]，快递员正在派送' },
      { time: '2023-05-22 18:30:00', content: '快件已到达[北京转运中心]' },
      { time: '2023-05-22 09:15:00', content: '快件已从[上海市浦东新区]发出' },
      { time: '2023-05-21 20:30:00', content: '快件已到达[上海转运中心]' },
      { time: '2023-05-21 09:30:00', content: '商家已发货' }
    ]
  }
  
  logisticsVisible.value = true
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await updateOrderStatus(row.id, { status: 'cancelled' })
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '订单取消成功'
      })
      
      // 刷新数据
      fetchData()
    } catch (error) {
      console.error('订单取消失败', error)
      ElMessage({
        type: 'error',
        message: '订单取消失败'
      })
    }
  }).catch(() => {})
}

// 删除订单
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该订单吗？删除后将无法恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际应用中应该调用API
      // await deleteOrder(row.id)
      
      // 模拟成功
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      
      // 刷新数据
      fetchData()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage({
        type: 'error',
        message: '删除失败'
      })
    }
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.orders-container {
  .search-card {
    margin-bottom: 20px;
  }
  
  .statistics-container {
    margin-bottom: 20px;
    
    .statistics-card {
      text-align: center;
      padding: 10px 0;
      
      .statistics-title {
        font-size: 14px;
        color: #999;
        margin-bottom: 10px;
      }
      
      .statistics-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      
      .statistics-compare {
        font-size: 13px;
        color: #999;
        
        .up {
          color: #f56c6c;
        }
        
        .down {
          color: #67c23a;
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .logistics-timeline {
    margin-top: 15px;
    padding: 10px;
  }
}
</style> 